﻿using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Aierp.Utility;
using Microsoft.AspNetCore.Mvc.Filters;
using Aierp.Utility.Core;
using Aierp.Utility.Data;
using System.Threading.Tasks;

namespace Aierp.Controllers
{
    [Route("api/[controller]")]
    public class ControllerBase : Controller
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string result = filterContext.HttpContext.Session.GetString(SysVisitor.SessionUserNameKey);
            if (result.IsEmpty())
            {
                var model = Create(false, ErrorCodeStatus.Unauthorized, "访问未获授权，请重新登录！");
                var contentResult = new ContentResult //这里使用ContentResult的原因是为了向前台输出自定义的json实体，与控制器返回保持一致，直接使用new JsonResult(model);的话，实体属性名称会变成小写。
                {
                    ContentType = "text/plain;charset=utf-8",
                    Content = model.ToJson()
                };
                filterContext.Result = contentResult;

                //HttpContext.Response.StatusCode = 401;//也可以直接返回状态码，但是表格控件等控件要重写，比较麻烦。
                return;
            }
            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// 检查用户是否具有管理员权限
        /// </summary>
        /// <returns></returns>
        public async Task<bool> CheckUser(SysVisitor sysVisitor)
        {
           bool canOperation = Convert.ToBoolean(sysVisitor.Session.GetString(SysVisitor.SessionIsAdminKey));

            if (!canOperation)
            {
              return await WriteUnauthJson();
            }
            return true;
        }

        /// <summary>
        /// 获取请求用户对象模型
        /// </summary>
        /// <returns></returns>
        public T GetModel<T>()
        {
            try
            {
                var request = HttpContext.Request;
                var json = request.Form["model"];
                var model = JSONhelper.ConvertToObject<T>(json);
                return model;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            
        }

        /// <summary>
        /// 获取List参数
        /// </summary>
        public PageRequestParam GetPageParam()
        {
            var request = HttpContext.Request;
            var pageParam = new PageRequestParam();
            pageParam.Order = request.Query["order"];
            pageParam.Limit = (request.Query["limit"].IsEmpty()) ? 100 : int.Parse(request.Query["limit"]);
            pageParam.Offset =(request.Query["offset"].IsEmpty()) ? 0 : int.Parse(request.Query["offset"]);

            string searchModel = request.Query["searchModel"];
            if (!searchModel.IsEmpty()) searchModel = searchModel.Trim();
            pageParam.SearchModel = searchModel;

            return pageParam;
        }

        /// <summary>
        /// 输出结果-操作成功
        /// </summary>
        /// <returns></returns>
        public async Task<bool> WriteSucessJson()
        {
            return await WriteJsonBase(true, ErrorCodeStatus.OK, "操作成功！");
           
        }

        /// <summary>
        /// 向前端返回结果，状态为ok,数据包含在resultObject
        /// </summary>
        /// <param name="resultObject"></param>
        /// <returns></returns>
        public async Task<bool> WriteResultJson(object resultObject)
        {
            return await WriteJsonBase(true, ErrorCodeStatus.OK, "", resultObject);
        }

        /// <summary>
        /// 输出结果-操作失败
        /// </summary>
        /// <returns></returns>
        public async Task<bool> WriteFailJson()
        {
            return await WriteJsonBase(false, ErrorCodeStatus.Failed);
        }

        /// <summary>
        /// 输出结果-操作失败
        /// </summary>
        /// <returns></returns>
        public async Task<bool> WriteFailJson(object resultObjec,string mess)
        {
            return await WriteJsonBase(false, ErrorCodeStatus.Failed, mess,resultObjec);
        }

        /// <summary>
        /// 写入未授权结果
        /// </summary>
        /// <returns></returns>
        public async Task<bool> WriteUnauthJson()
        {
            return await WriteJsonBase(false, ErrorCodeStatus.Unauthorized, "没有足够的权限进行操作");
        }

        /// <summary>
        /// 写入指定原因的错误信息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task<bool> WriteSpecReasonJson(string message)
        {
            return await WriteJsonBase(false, ErrorCodeStatus.Failed, message);
        }

        /// <summary>
        /// 输出结果基类
        /// </summary>
        /// <param name="isSucess"></param>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="resultObject"></param>
        /// <returns></returns>
        private async Task<bool> WriteJsonBase(bool isSucess, ErrorCodeStatus errorCode, string message = "操作失败", object resultObject = null)
        {
            await WriteJsonAsync(Create(isSucess, errorCode, message, resultObject));
            return isSucess;
        }

        /// <summary>
        /// 生成返回结果
        /// </summary>
        /// <param name="isSucess"></param>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="resultObject"></param>
        /// <returns></returns>
        public ResponseModel Create(bool isSucess, ErrorCodeStatus errorCode, string message = "操作失败", object resultObject = null)
        {
            return ResponseResult.Create(isSucess, errorCode, message, resultObject);
        }

        /// <summary>
        /// 向前端异步输出json
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public async Task WriteJsonAsync(object o)
        {
            Response.ContentType = "text/plain;charset=utf-8";
            //await Response.WriteAsync(ret, System.Text.Encoding.GetEncoding("GBK"));
            await Response.WriteAsync(o.ToJson());
        }

        /// <summary>
        /// 向前端异步输出
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public async Task WriteAsync(string str)
        {
            Response.ContentType = "text/plain;charset=utf-8";
            await Response.WriteAsync(str);
            //await Response.WriteAsync(str, System.Text.Encoding.GetEncoding("GBK"));
        }
    }
}
